'use strict'
/**
 * ExcelUtil
 * 你是一段成熟的代码，要学会自己改bug  ----我是小尾巴
 */

import xlsx from 'xlsx'

/**
 * 读取excel表格的信息
 * @param file
 * @param fieldIndex
 * @param dataIndex
 * @returns {Promise<*>}
 */
export const readExcel = async (file, fieldIndex, dataIndex) => {
  return new Promise(resolve => {
    const fileReader = new FileReader()
    fileReader.onload = ev => {
      const workbook = xlsx.read(ev.target.result, { type: 'binary' })
      // 取第一张表
      const sheetName = workbook.SheetNames[0]
      // 生成json表格内容
      const map = {}
      Object.entries(workbook.Sheets[sheetName]).filter(([key, value]) => !key.startsWith('!')).forEach(([key, value]) => {
        const num = Number(key.replace(/[a-zA-Z]/g, ''))
        const char = key.replace(/[0-9]/g, '')
        if (!map[num]) {
          map[num] = {}
        }
        map[num][char] = value
      })
      // 解析表头
      const fieldArray = Object.entries(map[fieldIndex]).filter(([key, value]) => !!value.c).map(([key, value]) => ({
        field: value.c[0].t,
        text: value.v,
        col: key
      }))
      // console.log(fieldArray)
      // 解析内容数据
      let index = dataIndex
      const list = []
      while (map[index]) {
        const row = map[index]
        const object = {}
        fieldArray.forEach(item => {
          object[item.field] = row[item.col] ? row[item.col].v : ''
        })
        list.push(object)
        index++
      }
      resolve({
        fieldArray,
        list
      })
    }
    fileReader.readAsBinaryString(file)
  })
}
